<template>
  <div class="home">
    <!-- 下拉刷新 -->
    <van-pull-refresh
      v-model="isLoading"
      :success-text="isSelectsuccess"
      @refresh="selectShua"
      :success-duration="1000"
    >
      <!-- list列表 -->
      <van-list
        v-model="loading"
        @load="getList"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem
          v-for="item in dataList"
          :key="item.art_id"
          :article="item"
        />
      </van-list>
      <!-- /list列表 -->
    </van-pull-refresh>
  </div>
</template>

<script>
import { Article } from "@/api/article.js";
import ArticleItem from "./Article-item.vue";

export default {
  created() {
    // this.getList();
  },
  data() {
    return {
      dataList: [],
      time_pre: new Date(), //请求的时间
      //   加载中
      loading: false,
      //   是否到底
      finished: false,
      // 加载失败
      error: false,
      // 下拉刷新
      isLoading: false,
      isSelectsuccess: "",
    };
  },
  props: {
    channles: {
      type: Object,
      require: true,
    },
  },
  methods: {
    async getList() {
      // console.log(this.time_pre);
      if (!this.time_pre) {
        this.finished = true;
        return;
      }
      try {
        const { data: res } = await Article({
          channel_id: this.channles.id, // 当前id
          timestamp: this.time_pre, //当前时间戳
        });

        // 设置加载失败  用来调试
        if (Math.random() > 0.2) {
          // 把 json 转成对象，如果不是  json 就报错，然后下面就可以捕获到了
          // JSON.parse("随机");
        }

        // 追加到 dataList
        if (this.isLoading) {
          this.dataList.unshift(...res.data.results);
          this.isSelectsuccess = "刷新成功";
          this.isLoading = false;
        } else {
          this.dataList.push(...res.data.results);
        }

        // 加载状态结束
        this.loading = false;
        this.time_pre = res.data.pre_timestamp;
      } catch (err) {
        console.log(err);
        this.isSelectsuccess = "刷新失败";
        this.isLoading = false;

        this.error = true;
        this.loading = false;
      }
    },
    selectShua() {
      this.getList();
      // function findScroll(element) {
      //   element.onscroll = function () {
      //     console.log(element);
      //   };
      //   Array.from(element.children).forEach(findScroll);
      // }
      // findScroll(document.body);
    },
  },
  components: {
    ArticleItem,
  },
};
</script>

<style lang="less" scoped>
.home {
  padding-top: 174px;
  height: 94vh;
  overflow-y: auto;
  box-sizing: border-box;
}
</style>